import api from '@/store/api';
import i18n from '@/i18n';
import { useGlobalStore } from '@/store/global';
const { t } = i18n.global as any;

export const usePowerControlStore = defineStore('powerControl', () => {
  const powerCapValue = ref(0);
  const powerConsumptionValue = ref(0);
  const powerChartData1 = ref([] as any[]); // current power chart data.
  const powerChartData1Interval = ref(undefined as NodeJS.Timeout | undefined); // current power chart data Interval.
  const ReadingRangeMax = ref(100);
  const startCalculateTime = ref(new Date());
  const calculateTime = ref(0);
  const totalConsumedPower = ref(0);
  const averagePower = ref(0);
  const currentPeakPower = ref(0);
  const historyInfo = ref([]);
  const chassisId = ref([] as string[]);
  const powerChassisId = ref('');
  const duringCalculateTime = ref(0);

  const powerConsumptionValueComputed = computed(() =>
    powerConsumptionValue.value.toFixed(1),
  );
  const totalConsumedPowerComputed = computed(() =>
    parseInt(totalConsumedPower.value as unknown as string),
  );
  const averagePowerComputed = computed(() =>
    parseInt(averagePower.value as unknown as string),
  );
  const currentPeakPowerComputed = computed(() =>
    parseInt(currentPeakPower.value as unknown as string),
  );

  const setPowerCapValue = (value: number) => {
    powerCapValue.value = value;
  };

  const setPowerConsumptionValue = (value: number) => {
    powerConsumptionValue.value = value;
  };
  // Set power chart data currently.
  const setpowerChartData1 = () => {
    const step = 2;
    powerChartData1Interval.value = setInterval(async () => {
      const globalStore = useGlobalStore();
      await globalStore.getBmcTime();
      const now = globalStore.bmcTime;
      if (powerChartData1.value.length <= 30) {
        powerChartData1.value.push([now, powerConsumptionValue.value]);
      } else {
        powerChartData1.value.shift();
        powerChartData1.value.push([now, powerConsumptionValue.value]);
      }
      calculateTime.value += step;
      totalConsumedPower.value += step * powerConsumptionValue.value;
      averagePower.value = totalConsumedPower.value / calculateTime.value;
    }, step * 1000);
  };
  const setReadingRangeMax = (RangeMax: any) => {
    ReadingRangeMax.value = RangeMax;
  };
  const setStartCalculateTime = (time: any) => {
    startCalculateTime.value = time;
  };
  const setHistoryInfo = (Info: any) => {
    historyInfo.value = Info;
  };
  const setChassisId = (Id: string[]) => {
    chassisId.value = Id;
  };
  const setPowerChassisId = (Id: string[]) => {
    powerChassisId.value = Id[0];
  };
  const setCurrentPeakPower = (Power: any) => {
    currentPeakPower.value = Power;
  };

  const getPowerControl = async () => {
    const PowerChassisId = powerChassisId.value;
    if (!PowerChassisId) {
      throw t('pagePower.msgBox.noPower') as string;
    }
    return await api
      .get(`/redfish/v1/Chassis/${PowerChassisId}/Power`)
      .then(({ data }) => {
        const powerControl = data.PowerControl;
        const powerCap = powerControl[0].PowerLimit.LimitInWatts;
        // If system is powered off, power consumption does not exist in the PowerControl
        const powerConsumption = powerControl[0].PowerConsumedWatts;

        setPowerCapValue(powerCap);
        setPowerConsumptionValue(powerConsumption);
      })
      .catch((error) => {
        console.log('Power control', error);
        throw error;
      });
  };
  const setPowerControl = async (powerCapValue: number) => {
    const PowerChassisId = powerChassisId.value;
    const data = {
      PowerControl: [{ PowerLimit: { LimitInWatts: powerCapValue } }],
    };

    return await api
      .patch(`/redfish/v1/Chassis/${PowerChassisId}/Power`, data)
      .then(() => t('pageServerPowerOperations.toast.successSaveSettings'))
      .catch((error) => {
        console.log(error);
        throw new Error(
          t('pageServerPowerOperations.toast.errorSaveSettings') as string,
        );
      });
  };
  const getReadingRangeMax = async () => {
    return await new Promise((resolve) => {
      if (currentPeakPower.value > 100) {
        const ReadingRangeMax = currentPeakPower.value + 10;
        setReadingRangeMax(ReadingRangeMax);
      }
      resolve(1);
    });
  };
  const startCalculate = async () => {
    // Clear calculating time.
    calculateTime.value = 0;
    totalConsumedPower.value = 0;
    averagePower.value = 0;

    // Set start calculating time.
    const globalStore = useGlobalStore();
    await globalStore.getBmcTime();
    const startCalculateTime = globalStore.bmcTime;
    setStartCalculateTime(startCalculateTime);
  };
  const getChassisId = async () => {
    const chassisId: string[] = [];
    await api.get('/redfish/v1/Chassis/').then(({ data: { Members } }) => {
      for (const member of Members) {
        const chassisUrl = Object.values(member)[0] as string;
        chassisId.push(chassisUrl.split('/')[chassisUrl.split('/').length - 1]);
      }
    });
    setChassisId(chassisId);
    return chassisId;
  };
  // Get the Chassis ID whose Power page contains OEM and PowerConsumedWatts.
  const getPowerChassisId = async () => {
    const chassisId = await getChassisId();
    const promises: Promise<any>[] = [];
    chassisId.forEach((id: string) => {
      const p = api
        .get(`/redfish/v1/Chassis/${id}/Power`)
        .then(({ data }) => {
          if (!data.PowerControl[0].Oem) {
            chassisId.pop();
          }
        })
        .catch((error) => {
          console.log(error);
        });
      promises.push(p);
    });
    await Promise.all(promises);
    setPowerChassisId(chassisId);
    return chassisId;
  };
  const getHistoryInfo = async () => {
    const PowerChassisId = powerChassisId.value;
    const promise1 = api
      .get(`/redfish/v1/Chassis/${PowerChassisId}/Power`)
      .then(({ data }) => {
        const OemUrl = data.PowerControl[0].Oem['@odata.id'];
        return OemUrl;
      })
      .then(async (OemUrl) => {
        const promise2 = api.get(OemUrl).then(({ data: { Data } }) => {
          setHistoryInfo(Data);
        });
        await Promise.all([promise2]);
      })
      .catch((error) => {
        return error;
      });
    await Promise.all([promise1]).then(
      api.spread((value) => {
        // Only output error messages.
        if (value) {
          console.log(value);
        }
      }),
    );
  };

  return {
    powerCapValue,
    powerConsumptionValue,
    powerChartData1,
    powerChartData1Interval,
    ReadingRangeMax,
    startCalculateTime,
    calculateTime,
    totalConsumedPower,
    averagePower,
    currentPeakPower,
    historyInfo,
    chassisId,
    powerChassisId,
    duringCalculateTime,
    powerConsumptionValueComputed,
    totalConsumedPowerComputed,
    averagePowerComputed,
    currentPeakPowerComputed,
    setPowerCapValue,
    setPowerConsumptionValue,
    setpowerChartData1,
    setReadingRangeMax,
    setStartCalculateTime,
    setHistoryInfo,
    setChassisId,
    setPowerChassisId,
    setCurrentPeakPower,
    getPowerControl,
    setPowerControl,
    getReadingRangeMax,
    startCalculate,
    getChassisId,
    getPowerChassisId,
    getHistoryInfo,
  };
});
